<?php
//话题
namespace app\api\controller;
use app\api\controller\CommonController;
use app\api\model\PortalPostModel;
use think\Db;
use think\Validate;
class StudyclubthemeController extends CommonController
{
    /**
     * 话题分类
     */
    public function themecategory()
    {
        $category = Db::name('portal_category')->where('parent_id', 5)->field('id,name')->select();
        if(empty($category)){
            return returnJson(3003, $this->errTips[3003]);
        }
        return returnJson(200, '', $category);
    }

    /**
     * 话题发布
     * @params string token_key 访问密钥
     * @params string theme_content 内容(限制500字)
     * @params string theme_title 标题
     * @params int theme_cate_id 分类id
     * @params string theme_keyword 话题关键字
     *
     */
    public function themepublish()
    {
        $token_key = input('post.token_key');
        $theme_content = input('post.theme_content');
        $theme_title = input('post.theme_title');
        $theme_cate_id = input('post.theme_cate_id');
        $theme_keyword = input('post.theme_keyword');
        $rule =[
            'token_key' => 'require',
            'theme_content' => 'require|length:1,500',
            'theme_title' => 'require|length:1,30',
            'theme_cate_id' => 'require|number|egt:1',
            'theme_keyword' => 'require|length:1,15',//‘四通八达，五湖四海，六神无主’（14个）
        ];
        $msg = [
            'token_key.require' => 4002,
            'theme_content.require' => 4002,
            'theme_content.length' => 2007,
            'theme_title.require' => 4002,
            'theme_title.length' => 2006,
            'theme_cate_id.require' => 4002,
            'theme_cate_id.number' => 4004,
            'theme_cate_id.egt' => 4006,
            'theme_keyword.require' => 4002,
            'theme_keyword.length' => 2008,
        ];
        $data = [
            'token_key' => $token_key,
            'theme_content' => $theme_content,
            'theme_title' => $theme_title,
            'theme_cate_id' => $theme_cate_id,
            'theme_keyword' => $theme_keyword
        ];
        $validate = new Validate($rule, $msg);
        $checkParam = $validate->check($data);
        if(!$checkParam){
            $errcode = $validate->getError();
            return returnJson($errcode, $this->errTips[$errcode]);
        }
        //验证关键词
        $explodes  = explode('，',  $theme_keyword);
        foreach ($explodes as $exv){
            if(!empty($exv)){
                $exvs[] = $exv;
            }
        }
        if(count($exvs) > 3){
            return returnJson(2008, $this->errTips[2008]);
        }
        if((mb_strlen($exvs[0]) > 4) || (mb_strlen($exvs[1]) > 4) || (mb_strlen($exvs[2]) > 4)){
            return returnJson(2009, $this->errTips[2009]);
        }
        $impolode = implode('，', $exvs);

        //验证用户
        $verifyToken = $this->verifyToken($token_key);
        if ( $verifyToken != '1111') {return $verifyToken;}
        $loginUserId = $this->user_id;
//        $loginUserId = 1;
        $cateInit = Db::name('portal_category');
        $verifyCate = $cateInit->where('parent_id', 5)->field('id,name')->select();//验证分类
        if(empty($verifyCate)){
            return returnJson(2004, $this->errTips[2004]);
        }
        foreach ($verifyCate as $cv){
            $cateid_Array[] = $cv['id'];
        }
        if(!in_array($theme_cate_id, $cateid_Array)){
            return returnJson(2004, $this->errTips[2004]);
        }

        $insertData = [
            'post_title' => $theme_title,
            'post_content' => $theme_content,
            'post_keywords' => $impolode,
            'cate_id' => $theme_cate_id,
            'user_id' => $loginUserId,
            'post_status' => 1,
            'create_time' => CURRENT_TIME,
            'update_time' => CURRENT_TIME,
            'published_time' => CURRENT_TIME
        ];
        $portalPostInit = new PortalPostModel();
        $insertResult = $portalPostInit->insertGetId($insertData);
        if($insertResult){
            return returnJson(200, 'success');
        }
        return returnJson(3002, $this->errTips[3002]);
    }

    /**
     * 话题数据列表
     * @params int theme_cate_id 话题分类
     * @params int page 分页
     * @params int limit 每页显示数
     * @params string token_key 访问密钥
     */
    public function themelist()
    {
        $theme_id = input('post.theme_cate_id');
        $page = input('post.page');
        $limit = input('post.limit');
        $token = input('post.token_key');

        $rule = [
            'theme_id' => 'require|number|egt:1',
            'page' => 'require|number|egt:1',
            'limit' => 'require|number|egt:1'
        ];
        $msg = [
            'theme_id.require' => 4002,
            'theme_id.number' => 4004,
            'theme_id.egt' => 4006,
            'page.require' => 4002,
            'page.number' => 4004,
            'page.egt' => 4006,
            'limit.require' => 4002,
            'limit.number' => 4004,
            'limit.egt' => 4006,
        ];
        $data['theme_id'] = $theme_id;
        $data['page'] = $page;
        $data['limit'] = $limit;

        $validate = new Validate($rule, $msg);
        $checkParams = $validate->check($data);
        if(!$checkParams){
            $errcode = $validate->getError();
            return returnJson($errcode,  $this->errTips[$errcode]);
        }
        $checkCategory = Db::name('portal_category')->where('parent_id', 5)->field('id')->select();
        foreach($checkCategory as $ccv){
            $cateArray[] = $ccv['id'];
        }
        if(!in_array($theme_id, $cateArray)){
            return returnJson(3003, '无效分类theme_cate_id');
        }
        $portalPost_m = new PortalPostModel();
        $whereMap = [
            'post_status' => 1,
            'delete_time' => 0,
            'cate_id' => $theme_id,
        ];
        //字段is_top置顶（是否置顶;1:置顶;0:不置顶）  字段recommended推荐（是否推荐;1:推荐;0:不推荐）
        $themeQueryResult = $portalPost_m->where($whereMap)->limit(($page - 1) * $limit, $limit)->order('is_top DESC,recommended DESC,create_time DESC ')->field('id,user_id,post_content,published_time,create_time,post_title,is_top,recommended,post_keywords')->select();
        $count = $portalPost_m->where($whereMap)->count();
        if(!empty($token)){
            $verifyToken = $this->verifyToken($token);
            if ( $verifyToken != '1111') {return $verifyToken;}
            $loginUserId = $this->user_id;
        }

        foreach ($themeQueryResult as $thvs){
            $commemttotal = $thvs->getcomments;//获取评论
            $liketotal = $thvs->getlickcount;//获取点赞
            $favoritetotal = $thvs->getfavoritecount;//获取收藏
            $getuserinfo = $thvs->getuserinfo;//获取用户信息
            $singleData = $thvs->toArray();
            $singleData['user_name'] = $getuserinfo['staff_name'];
            $singleData['user_name'] = $getuserinfo['staff_name'];
            $singleData['commentCount'] = count($commemttotal);
            $singleData['likeCount'] = count($liketotal);
            $singleData['favoriteCount'] = count($favoritetotal);

            $singleData['loginUserIsColloct'] =  0;
            $singleData['loginUserIsLike'] = 0;
            if(isset($loginUserId)){
                $favoriteMap = [
                    'object_id' => $singleData['id'],
                    'user_id' => $loginUserId,
                    'type_status' => 1
                ];
                //loginUserIsColloct等于1收藏   loginUserIsColloct等于0不收藏
                $singleData['loginUserIsColloct'] = ($portalPost_m->getloginuserfavoritestatus($favoriteMap)) ? 1 : 0;
                $singleData['loginUserIsLike'] = ($portalPost_m->getloginuserlikestatus($favoriteMap)) ? 1 : 0;
            }
            unset($singleData['getcomments']);
            unset($singleData['getlickcount']);
            unset($singleData['getfavoritecount']);
            unset($singleData['getuserinfo']);
            $allData[] = $singleData;
        }
        return returnJson(200, '', ['count'=>$count, 'data'=>$allData]);
    }
}